<script setup lang="ts">
import { ref } from 'vue';
import { useSkuInfo } from '@/stores/skuInfo';
import { useRouter, useRoute } from 'vue-router';
import type { SkuItem } from '@/types/product';
import { showToast, showSuccessToast } from 'vant';
import { updSku } from '@/common/api/hbMarket';

const skuInfo = useSkuInfo();
const router = useRouter();
const route = useRoute();

const pid = ref((route.query?.pid as string) || '');
const loading = ref(false);
const skuInfoList = ref<SkuItem[]>([]); // sku列表
skuInfoList.value = skuInfo.state.skuInfoList;
const skuAttrName = ref(''); // 添加sku名称

// 数值大于0校验
const priceValidator = (val: string | number) => Number(val) >= 0;
//字符串转base64
const encodeProinfo = (obj: Object) => {
  // 对字符串进行编码 对编码的字符串转化base64
  return btoa(encodeURIComponent(JSON.stringify(obj)));
};

const onSubmit = async () => {
  loading.value = true;
  try {
    const skuinfo = encodeProinfo(skuInfoList.value.map((v, i) => ({ ...v, skuid: i })));
    const res = await updSku({ pid: pid.value, skuinfo });
    skuInfo.setSkuInfoList(skuInfoList.value);
    showSuccessToast(res.message);
    router.back();
  } catch {
    /** empty */
  } finally {
    loading.value = false;
  }
  // skuInfo.setSkuInfoList(skuInfoList.value);
  // router.back();
};

// 添加规格
const addSkuAttr = () => {
  const fidx = skuInfoList.value.findIndex((v) => v.skuname === skuAttrName.value);
  if (fidx > -1) {
    return showToast('不能添加重复规格');
  }
  skuInfoList.value.push({
    skuname: skuAttrName.value, // 规格名称
    images: '',
    price: 0, // 原价
    skuprice: 0, // 现价
    stock: 0, // 库存
  });
  skuAttrName.value = '';
};
</script>
<template>
  <div class="productSkuForm">
    <van-cell-group inset>
      <van-field v-model.trim="skuAttrName" center clearable label="规格名称" placeholder="请输入规格名称">
        <template #button>
          <van-button size="small" type="primary" @click="addSkuAttr">添加规格</van-button>
        </template>
      </van-field>
    </van-cell-group>

    <van-form class="pb-20" @submit="onSubmit" scroll-to-error>
      <van-cell-group inset v-for="item in skuInfoList" :key="item.skuname" class="!mt-4">
        <van-field
          v-model="item.skuname"
          name="skuprice"
          label="规格名称"
          placeholder="规格名称"
          :rules="[{ required: true, message: '请填写规格名称' }]"
        />
        <van-field
          v-model="item.price"
          name="price"
          label="零售价格"
          placeholder="零售价格"
          :rules="[
            { required: true, message: '请填写零售价格' },
            { validator: priceValidator, message: '数值不能小于0' },
          ]"
        />
        <van-field
          v-model="item.skuprice"
          name="skuprice"
          label="积分数量"
          placeholder="积分数量"
          :rules="[
            { required: true, message: '请填写积分数量' },
            { validator: priceValidator, message: '数值不能小于0' },
          ]"
        />
        <van-field
          v-model="item.stock"
          name="stock"
          type="number"
          label="库存"
          placeholder="库存"
          :rules="[
            { required: true, message: '请填写库存' },
            { validator: priceValidator, message: '数值不能小于0' },
          ]"
        />
      </van-cell-group>
      <div class="fixed w-full bottom-0 p-4">
        <van-button round block type="primary" native-type="submit"> 提交 </van-button>
        <!-- 底部安全区 -->
        <div class="van-safe-area-bottom"></div>
      </div>
      <!-- 底部安全区 -->
      <div class="van-safe-area-bottom"></div>
    </van-form>
    <van-empty v-if="!skuInfoList.length" description="规格内容为空" />
  </div>
</template>
<style lang="less" scoped>
.productSkuForm {
  min-height: 100%;
  overflow-y: auto;
  background: #f7f8fa;
  padding-top: 15px;
  :deep(.absolute-cell-value) {
    position: absolute;
    right: 10px;
    top: 10px;
  }
}
</style>
